﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.WebControls;

namespace ZhukBlogLinqExamples.FieldTypes.CustomUser.Controls
{
    public class CustomUserFieldControlMulti : MultipleLookupField 
    {
        [SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
        protected override void CreateChildControls()
        {
            if (IsFieldValueCached)
            {
                base.CreateChildControls();
            }
            else if (Field != null)
            {
                if (ControlMode != SPControlMode.Display)
                {
                    _picker = new CustomUserFieldPicker { CustomProperty = string.Empty };
                    Controls.Add(_picker);
                    SetFieldControlValue(Page.IsPostBack ? Value : ItemFieldValue);
                }

            }
        }

        private CustomUserFieldPicker _picker;

        private void SetFieldControlValue(object value)
        {
            _picker.Entities.Clear();

            var list = new ArrayList();

            if (ControlMode == SPControlMode.New && _picker.Entities.Count == 0)
            {
                //        //DEFAULT VALUE
            }
            else
            {
                if (value != null && value.GetType().Name == typeof(string).Name)
                {
                    SPFieldLookupValueCollection val = new SPFieldLookupValueCollection((string)value);
                    list.AddRange((val).Select(l => l.ToPickerEntity()).ToArray());
                }
                else if (value is SPFieldLookupValue)
                {
                    list.Add(((SPFieldLookupValue)value).ToPickerEntity());
                }
                else if (value is SPFieldLookupValueCollection)
                {
                    list.AddRange(((SPFieldLookupValueCollection)value).Select(l => l.ToPickerEntity()).ToArray());
                }
            }
            _picker.UpdateEntities(list);
        }
    }
}
